package controllers

import (
	"ABlog/util"
	"fmt"
	"github.com/astaxie/beego"
	"io/ioutil"
	"os"
)

type ApiSaveArticleController struct {
	beego.Controller
}

func (c *ApiSaveArticleController) Post() {
	mdContent := c.GetString("mdContent", "")
	id := c.GetString("id", "0")
	nid := c.GetString("nid", "0")
	var filePath string
	var code int = 200
	if nid == "0" || nid == "" {
		// perform create a new article
		nid = util.GenArticleId()
	} else {
		// save to existed article
	}
	filePath = util.GetArticlePath(nid)
	err := ioutil.WriteFile(filePath, []byte(mdContent), 0666)
	if nil != err {
		code = 500
	} else {
		code = 200
	}

	// delete old article
	if id != nid {
		os.Remove(util.GetArticlePath(id))
	}

	c.Data["json"] = fmt.Sprintf("{\"code\":%d, \"id\":\"%s\"}", code, nid)
	c.ServeJSON()
}

func (c *ApiSaveArticleController) exist(articleId string) bool {
	b, _ := util.PathExists(util.GetArticlePath(articleId))
	return b
}
